#include "ClientHandler.h"

ClientHandler::ClientHandler() :
	request_tk(Configuration::get_property("request_list_token").at(0)),
			separator_tk(Configuration::get_property("separator_token").at(0)) {
	pthread_mutex_init(&ch_mutex, NULL);
	userProfileManager = UserProfileManager::getInstance();
}

ClientHandler::~ClientHandler() {
	pthread_mutex_destroy(&ch_mutex);
	delete userProfileManager;
}

vector<string> ClientHandler::parse_request(string& message) {
	vector<string> sv;
	unsigned i = 0, j = message.find(separator_tk, 0);

	while (j != string::npos) {
		sv.push_back(message.substr(i, j - i));
		i = j + 1;
		j = message.find(separator_tk, i);
	}
	sv.push_back(message.substr(i));

	return sv;
}

string ClientHandler::parse_response(vector<string> message) {
	if (message.empty())
		return "";

	string response(message.front());
	response += separator_tk;
	for (unsigned i = 1; i != message.size(); i++) {
		response += message.at(i);
		if (i != message.size() - 1)
			response += separator_tk;
	}

	return response;
}

void ClientHandler::push_request(string& message) {
	request_messages.push(message);
}

string ClientHandler::pop_response() {
	if (response_messages.empty())
		return "";

	pthread_mutex_lock(&ch_mutex);

	string response = response_messages.front();
	response_messages.pop();

	pthread_mutex_unlock(&ch_mutex);

	return response;
}

void ClientHandler::proccess_requests() {
	pthread_mutex_lock(&ch_mutex);

	while (!request_messages.empty()) {
		vector<string> msg = parse_request(request_messages.front());
		string response;
		if (msg.at(2).at(0) == request_tk) {
			response = parse_response(cf.getTopNList(msg.at(0), atoi(
					msg.at(1).c_str())));
		} else {
			userProfileManager->updateUserProfile(msg.at(0), atoi(
					msg.at(1).c_str()), atoi(msg.at(2).c_str()));
			response = msg.at(0);
		}

		response_messages.push(response);
		request_messages.pop();
	}

	pthread_mutex_unlock(&ch_mutex);
}
